package com.example.shop_2212.fg

import android.content.Context
import android.os.Bundle
import android.os.Handler
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.example.base.entity.Roll
import com.example.base.mvvm.BaseFragment
import com.example.base.mvvm.BaseViewFragment
import com.example.base.net.Const
import com.example.shop_2212.R
import com.example.shop_2212.adapter.*
import com.example.shop_2212.databinding.FragmentHomeBinding
import com.example.shop_2212.fgviewmodel.HomeViewModel
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.youth.banner.BannerConfig
import com.youth.banner.loader.ImageLoader
import java.util.Timer
import kotlin.concurrent.timerTask

class HomeFragment : BaseFragment<FragmentHomeBinding,HomeViewModel>() {
    //定义存放imgs的集合
    val imgs = mutableListOf<String>()
    lateinit var menuAdapter: MenuAdapter
    lateinit var newsAdapter: NewsAdapter
    //定时器相关
    lateinit var timer: Timer
    val handler = Handler()
    var index = 0//目前显示的rv的下标

    lateinit var couponAdapter: CouponAdapter

    lateinit var goodsAdapter: GoodsAdapter
    lateinit var goodsAdapter1: GoodsMutAdapter

    var page = 1//当前页面
    override fun getLayout(): Int  = R.layout.fragment_home

    override fun getViewModel(): Class<HomeViewModel>  = HomeViewModel::class.java

    override fun initView() {
        //初始化商品
        goodsAdapter = GoodsAdapter()
        binding.rvCuxiao.adapter = goodsAdapter
        binding.rvCuxiao.layoutManager = GridLayoutManager(context,3)

        goodsAdapter1 = GoodsMutAdapter()
        binding.rvCuxiao1.adapter = goodsAdapter1
        binding.rvCuxiao1.layoutManager = GridLayoutManager(context,2)
        //初始化菜单rv
        menuAdapter = MenuAdapter()
        binding.rvMenu.adapter = menuAdapter
        binding.rvMenu.layoutManager = GridLayoutManager(context,5)
        //初始化新闻rv
        newsAdapter = NewsAdapter()
        binding.rvNews.adapter = newsAdapter
        binding.rvNews.layoutManager = LinearLayoutManager(context)
        //请求首页数据
        viewModel.index()
        //让新闻中的数据滚动起来  结合定时器，每2秒让数据变化一次
        //binding.rvNews.scrollToPosition()//让数据滚到到指定位置
        timer = Timer()
        timer.schedule(timerTask {
                      handler.post {
                          binding.rvNews.scrollToPosition(index)
                          index++
                          if(index==newsAdapter.data.size){
                              index = 0
                          }

                      }
        },0,2000)

        //初始化优惠券
        couponAdapter = CouponAdapter()
        binding.rvCoupons.layoutManager = GridLayoutManager(context,1,GridLayoutManager.HORIZONTAL,false)
        binding.rvCoupons.adapter = couponAdapter
        viewModel.coupon("10","1","1")

        //优惠券点击
        couponAdapter.setOnItemClickListener { adapter, view, position ->
            if(!couponAdapter.data[position].isUse){//如果未领取
                viewModel.getCoupon(couponAdapter.data[position].id)
                couponAdapter.data[position].isUse = true
                (couponAdapter.getViewByPosition(position,R.id.tv_get) as TextView).text = "已领取"
            }
        }
        //点击跳转到搜索界面
        binding.clSearch.setOnClickListener {
            ARouter.getInstance().build("/app/SearchActivity").navigation()
        }
        //左滑删除
        ItemTouchHelper(object :ItemTouchHelper.Callback(){
            override fun getMovementFlags(
                recyclerView: RecyclerView,
                viewHolder: RecyclerView.ViewHolder
            ): Int {
               val left = ItemTouchHelper.LEFT //or ItemTouchHelper.RIGHT
                return makeMovementFlags(0,left)
            }

            override fun onMove(
                recyclerView: RecyclerView,
                viewHolder: RecyclerView.ViewHolder,
                target: RecyclerView.ViewHolder
            ): Boolean {
                return true
            }

            override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
                //滑动结果
                val position = viewHolder.layoutPosition
                goodsAdapter1.data.removeAt(position)
                goodsAdapter1.notifyDataSetChanged()
            }
        }).attachToRecyclerView(binding.rvCuxiao1)

        //刷新  加载更多
        binding.smart.setOnRefreshLoadMoreListener(object :OnRefreshLoadMoreListener{
            override fun onRefresh(refreshLayout: RefreshLayout) {
               //刷新
                page = 1
                viewModel.indexGoods1(1,3,page)
                binding.smart.finishRefresh()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                //加载更多
                page++
                viewModel.indexGoods1(1,3,page)
                binding.smart.finishLoadMore()
            }
        })

        //点击跳转到详情界面
        goodsAdapter.setOnItemClickListener { adapter, view, position ->
            ARouter.getInstance().build("/app/XqActivity").withInt("gid",goodsAdapter.data[position].id).navigation()
        }
        goodsAdapter1.setOnItemClickListener { adapter, view, position ->
            ARouter.getInstance().build("/app/XqActivity").withInt("gid",goodsAdapter1.data[position].id).navigation()
        }

    }

    override fun initData() {
        //解析数据
        viewModel.indexSuccess.observe(this){
            if(it.code==Const.RESULT_OK){
                it.data.banner.forEach {
                    imgs.add(it.pic)
                }
                binding.banner.setImages(imgs)
                    .setImageLoader(object :ImageLoader(){
                        override fun displayImage(
                            context: Context?,
                            path: Any?,
                            imageView: ImageView?
                        ) {
                            if (context != null) {
                                if (imageView != null) {
                                    Glide.with(context).load(path).transform(CenterCrop(),RoundedCorners(20)).into(imageView)
                                }
                            }
                        }
                    })
                    .setDelayTime(2000)//轮播时长
                    .setBannerStyle(BannerConfig.NUM_INDICATOR)//设置数字指示器
                    .start()
                //轮播图点击事件
                binding.banner.setOnBannerListener {
                    ToastUtils.showLong("点击的是$it 张图片")
                }
                //促销的轮播图
                binding.bannerCuxiao.setImages(imgs)
                    .setImageLoader(object :ImageLoader(){
                        override fun displayImage(
                            context: Context?,
                            path: Any?,
                            imageView: ImageView?
                        ) {
                            if (context != null) {
                                if (imageView != null) {
                                    Glide.with(context).load(path).transform(CenterCrop(),RoundedCorners(20)).into(imageView)
                                }
                            }
                        }
                    })
                    .start()
                //显示菜单数据
                menuAdapter.data.clear()
                menuAdapter.data.addAll(it.data.menus)
                menuAdapter.notifyDataSetChanged()

                //显示新闻数据
                newsAdapter.data.clear()
                newsAdapter.data.addAll(it.data.roll)
                newsAdapter.data.add(Roll(0,"新品限量抢，积分翻倍","",""))//为了模拟滚动的效果，添加了一条数据
                newsAdapter.notifyDataSetChanged()
                //显示具体分类名称
                binding.tvTitle.text = it.data.explosiveMoney[0].info
                binding.tvName.text = it.data.explosiveMoney[0].name
                //请求对应分类的数据
                viewModel.indexGoods(it.data.explosiveMoney[0].type.toInt(),3,1)

                binding.tvTitle1.text = it.data.explosiveMoney[1].info
                binding.tvName1.text = it.data.explosiveMoney[1].name
                //请求对应分类的数据
                viewModel.indexGoods1(it.data.explosiveMoney[1].type.toInt(),3,1)
            }
        }
        viewModel.couponSuccess.observe(this){
            if(it.code==Const.RESULT_OK){
                couponAdapter.data.clear()
                couponAdapter.data.addAll(it.data)
                couponAdapter.notifyDataSetChanged()
            }
        }
        viewModel.getCouponSuccess.observe(this){
            if(it.code==Const.RESULT_OK){
                ToastUtils.showLong(it.message)
                //可以重新查询
                //viewModel.coupon()
            }
        }
        viewModel.indexGoodSuccess.observe(this){
            if(it.code==Const.RESULT_OK){
                goodsAdapter.data.clear()
                goodsAdapter.data.addAll(it.data.list)
                goodsAdapter.notifyDataSetChanged()
            }
        }
        viewModel.indexGoodSuccess1.observe(this){
            if(it.code==Const.RESULT_OK){
                //目的呈现多布局
                it.data.list.forEachIndexed { index, goods ->
                    goods.type = index%2
                }
                if(page==1){
                    goodsAdapter1.data.clear()
                }
                goodsAdapter1.data.addAll(it.data.list)
                goodsAdapter1.notifyDataSetChanged()
                if(it.data.list.size==0){
                    ToastUtils.showLong("没有更多数据了")
                }
            }
        }
    }

}